{% extends 'knowledge/base.html' %}
{% load static %}

{% block title %}添加文档 - {{ collection_name }} - 知识库管理系统{% endblock %}

{% block extra_css %}
<link rel="stylesheet" href="{% static 'knowledge/css/simplemde.min.css' %}">
<style>
    .metadata-editor { height: 150px; }
    .content-editor { min-height: 300px; }
</style>
{% endblock %}

{% block content %}
<div class="max-w-4xl mx-auto">
    <div class="flex items-center mb-6">
        <a href="{% url 'knowledge:collection_detail' collection_name %}" class="text-neutral hover:text-primary mr-4">
            <i class="fa fa-arrow-left"></i>
        </a>
        <div>
            <h2 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-gray-800">添加文档</h2>
            <p class="text-neutral mt-1">添加新文档到集合: <span class="font-medium">{{ collection_name }}</span></p>
        </div>
    </div>

    <div class="bg-white rounded-xl p-6 md:p-8 card-shadow">
        <form method="post" class="space-y-6">
            {% csrf_token %}
            <div class="grid grid-cols-1 md:grid-cols-12 gap-6">
                <div class="md:col-span-12">
                    <label for="title" class="block text-sm font-medium text-gray-700 mb-1">文档标题 <span class="text-red-500">*</span></label>
                    <input type="text" id="title" name="title" required
                           class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary"
                           placeholder="输入文档标题">
                </div>

                <div class="md:col-span-12" style="z-index: 10000;">
                    <label for="content" class="block text-sm font-medium text-gray-700 mb-1">文档内容 <span class="text-red-500">*</span></label>
                    <textarea id="content" name="content"
                              class="w-full px-4 py-3 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary content-editor"
                              placeholder="输入文档内容..."></textarea>
                </div>

                <div class="md:col-span-12">
                    <label class="block text-sm font-medium text-gray-700 mb-1">元数据</label>
                    <div class="mb-2">
                        <table class="w-full" id="metadata-table">
                            <thead>
                                <tr>
                                    <th class="text-left pb-2 w-5/12">键</th>
                                    <th class="text-left pb-2 w-5/12">值</th>
                                    <th class="text-left pb-2 w-2/12"></th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr class="metadata-row">
                                    <td class="pr-2 pb-2">
                                        <input type="text" class="metadata-key w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="键名">
                                    </td>
                                    <td class="pr-2 pb-2">
                                        <input type="text" class="metadata-value w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="值">
                                    </td>
                                    <td class="pb-2 text-center">
                                        <button type="button" class="delete-row px-2 py-1 text-red-500 hover:text-red-700 rounded-lg" title="删除行">
                                            <i class="fa fa-trash"></i>
                                        </button>
                                    </td>
                                </tr>
                            </tbody>
                        </table>
                    </div>
                    
                    <div class="flex justify-start mb-2">
                        <button type="button" id="add-row" class="flex items-center px-3 py-1.5 bg-gray-100 text-gray-700 rounded-lg hover:bg-gray-200 transition-colors text-sm">
                            <i class="fa fa-plus mr-1"></i> 添加字段
                        </button>
                    </div>
                    
                    <!-- 隐藏的JSON输入框，用于表单提交 -->
                    <input type="hidden" id="metadata" name="metadata" value="{}">
                    <p class="mt-1 text-xs text-neutral">添加键值对形式的元数据，系统会自动添加标题到元数据中</p>
                    <p id="metadata-error" class="mt-1 text-xs text-red-500 hidden">元数据格式有误，请检查输入</p>
                </div>
            </div>

            <div class="pt-4 flex justify-end space-x-3 border-t border-gray-100">
                <a href="{% url 'knowledge:collection_detail' collection_name %}" class="px-4 py-2 border border-gray-300 rounded-lg text-gray-700 hover:bg-gray-50 transition-colors">
                    取消
                </a>
                <button type="submit" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors shadow-sm">
                    保存文档
                </button>
            </div>
        </form>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script src="{% static 'knowledge/js/simplemde.min.js' %}"></script>
<script>
// 初始化Markdown编辑器
var simplemde = new SimpleMDE({
  element: document.getElementById("content"),
  spellChecker: false,
  toolbar: [
    "bold", "italic", "strikethrough", "|",
    "heading-1", "heading-2", "heading-3", "|",
    "code", "quote", "unordered-list", "ordered-list", "link","|",
    "preview", "fullscreen", "guide","side-by-side"
  ]
});

// 添加表单验证
 document.querySelector('form').addEventListener('submit', function(e) {
    if (!simplemde.value().trim()) {
        e.preventDefault();
        alert('文档内容不能为空');
        // 聚焦到编辑器
        document.querySelector('.CodeMirror').focus();
    }
});


// 获取元素
const metadataInput = document.getElementById('metadata');
const metadataError = document.getElementById('metadata-error');
const metadataTable = document.getElementById('metadata-table');
const addRowBtn = document.getElementById('add-row');
const form = metadataInput.closest('form');

// 添加新行
function addNewRow() {
    const tbody = metadataTable.querySelector('tbody');
    const newRow = document.createElement('tr');
    newRow.className = 'metadata-row';
    newRow.innerHTML = `
        <td class="pr-2 pb-2">
            <input type="text" class="metadata-key w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="键名">
        </td>
        <td class="pr-2 pb-2">
            <input type="text" class="metadata-value w-full px-4 py-2 rounded-lg border border-gray-300 focus:outline-none focus:ring-2 focus:ring-primary/30 focus:border-primary" placeholder="值">
        </td>
        <td class="pb-2 text-center">
            <button type="button" class="delete-row px-2 py-1 text-red-500 hover:text-red-700 rounded-lg" title="删除行">
                <i class="fa fa-trash"></i>
            </button>
        </td>
    `;
    tbody.appendChild(newRow);
    
    // 为新行的删除按钮添加事件监听器
    const deleteBtn = newRow.querySelector('.delete-row');
    deleteBtn.addEventListener('click', function() {
        deleteRow(this);
    });
    
    // 为新行的输入框添加事件监听器
    const inputs = newRow.querySelectorAll('input');
    inputs.forEach(input => {
        input.addEventListener('input', updateMetadataJson);
    });
}

// 删除行
function deleteRow(button) {
    const row = button.closest('tr');
    const tbody = row.parentNode;
    
    // 如果只有一行，则清空输入而不是删除行
    if (tbody.children.length === 1) {
        const inputs = row.querySelectorAll('input');
        inputs.forEach(input => input.value = '');
    } else {
        row.remove();
    }
    
    updateMetadataJson();
}

// 将表格数据转换为JSON
function updateMetadataJson() {
    const rows = document.querySelectorAll('.metadata-row');
    const metadata = {};
    let isValid = true;
    
    rows.forEach(row => {
        const keyInput = row.querySelector('.metadata-key');
        const valueInput = row.querySelector('.metadata-value');
        const key = keyInput.value.trim();
        const value = valueInput.value.trim();
        
        if (key) {
            // 检查键是否重复
            if (metadata.hasOwnProperty(key)) {
                isValid = false;
                keyInput.classList.add('border-red-500');
            } else {
                keyInput.classList.remove('border-red-500');
                metadata[key] = value;
            }
        }
    });
    
    if (isValid) {
        metadataInput.value = Object.keys(metadata).length > 0 ? JSON.stringify(metadata) : '{}';
        metadataError.classList.add('hidden');
    } else {
        metadataError.textContent = '存在重复的键名，请修正';
        metadataError.classList.remove('hidden');
    }
    
    return isValid;
}

// 为添加行按钮添加事件监听器
addRowBtn.addEventListener('click', addNewRow);

// 为初始行的删除按钮添加事件监听器
document.querySelectorAll('.delete-row').forEach(button => {
    button.addEventListener('click', function() {
        deleteRow(this);
    });
});

// 为初始行的输入框添加事件监听器
document.querySelectorAll('.metadata-key, .metadata-value').forEach(input => {
    input.addEventListener('input', updateMetadataJson);
});

// 表单提交前验证
form.addEventListener('submit', function(e) {
    if (!updateMetadataJson()) {
        e.preventDefault();
        metadataError.classList.remove('hidden');
    }
});

// 初始化
updateMetadataJson();
</script>
{% endblock %}